// 创建DICOM数据服务
export class DicomDataService {
    constructor(baseUrl = 'http://192.168.31.186:8080/api/dicom') {
        this.baseUrl = baseUrl;
        // 七牛云配置常量（与后端保持一致）
        this.qiniuConfig = {
            bucket: 'zang-dicm',  // 与后端配置一致
            domain: 'dicom.jiannong.vip'  // 与后端配置一致
        };
    }
    
    /**
     * 获取序列图像信息
     */
    async getSeriesImages(studyInstanceUid, seriesInstanceUid) {
        try {
            const response = await fetch(
                `${this.baseUrl}/query/series/${studyInstanceUid}/${seriesInstanceUid}`
            );
            const result = await response.json();
            
            // 验证后端返回的七牛云配置
            if (result.qiniuConfig) {
                console.log('后端返回的七牛云配置:', result.qiniuConfig);
                // 检查配置是否与前端一致
                if (result.qiniuConfig.bucket !== this.qiniuConfig.bucket) {
                    console.warn('存储桶配置不一致:', {
                        frontend: this.qiniuConfig.bucket,
                        backend: result.qiniuConfig.bucket
                    });
                }
                if (result.qiniuConfig.domain !== this.qiniuConfig.domain) {
                    console.warn('域名配置不一致:', {
                        frontend: this.qiniuConfig.domain,
                        backend: result.qiniuConfig.domain
                    });
                }
            }
            
            return result;
        } catch (error) {
            console.error('获取序列图像失败:', error);
            throw error;
        }
    }
    
    /**
     * 从七牛云获取DICOM文件
     */
    async fetchDicomFromQiniu(ossUrl) {
        try {
            console.log('正在从七牛云获取DICOM文件:', ossUrl);
            
            // 验证URL是否包含正确的域名
            if (!ossUrl.includes(this.qiniuConfig.domain)) {
                console.warn('URL域名与配置不匹配:', {
                    url: ossUrl,
                    expectedDomain: this.qiniuConfig.domain
                });
            }
            
            const response = await fetch(ossUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/dicom, */*'
                }
            });
            
            if (!response.ok) {
                const errorText = await response.text();
                console.error('七牛云响应错误:', {
                    status: response.status,
                    statusText: response.statusText,
                    error: errorText
                });
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
            }
            
            return await response.arrayBuffer();
        } catch (error) {
            console.error('从七牛云获取DICOM文件失败:', error);
            throw error;
        }
    }
    
    /**
     * 创建图像ID列表（结合后端数据和七牛云地址）
     */
    async createImageIds(studyInstanceUid, seriesInstanceUid) {
        // 1. 从后端获取图像信息
        const seriesData = await this.getSeriesImages(studyInstanceUid, seriesInstanceUid);
        
        if (!seriesData.success || !seriesData.images) {
            throw new Error('获取图像信息失败');
        }
        
        // 2. 使用后端返回的配置，如果没有则使用本地配置
        const qiniuConfig = seriesData.qiniuConfig || this.qiniuConfig;
    
        // 3. 验证图像URL格式
        const validImages = seriesData.images.filter(image => {
            if (!image.ossUrl) {
                console.warn('图像缺少ossUrl:', image);
                return false;
            }
            return true;
        });
      
        console.log(validImages)
        if (validImages.length === 0) {
            throw new Error('没有有效的图像URL');
        }
        
        // 4. 构建图像ID列表
        const imageIds = validImages.map(image => {
            // 清理URL中的空格和特殊字符
            let cleanUrl = image.ossUrl.trim();
            
            // 确保URL使用正确的协议
            if (!cleanUrl.startsWith('http://') && !cleanUrl.startsWith('https://')) {
                cleanUrl = `http://${cleanUrl}`;
            }
            
            console.log('处理图像URL:', {
                original: image.ossUrl,
                cleaned: cleanUrl,
                sopInstanceUid: image.sopInstanceUid
            });
            
            // 使用自定义协议，包含OSS地址信息
            return `qiniu:${cleanUrl}?sopInstanceUid=${image.sopInstanceUid}&bucket=${qiniuConfig.bucket}`;
        });
        
        console.log(`成功创建 ${imageIds.length} 个图像ID`);
        
        return {
            imageIds,
            qiniuConfig,
            imageInfo: validImages
        };
    }
    
    /**
     * 验证七牛云配置
     */
    validateQiniuConfig() {
        const requiredFields = ['bucket', 'domain'];
        const missing = requiredFields.filter(field => !this.qiniuConfig[field]);
        
        if (missing.length > 0) {
            throw new Error(`七牛云配置缺少必要字段: ${missing.join(', ')}`);
        }
        
        console.log('七牛云配置验证通过:', this.qiniuConfig);
        return true;
    }

    /**
     * 获取检查列表 
     */
    async getStudyList(){

    }
}

// 创建默认实例
const dicomService = new DicomDataService();
export default dicomService;